<?php
namespace auth;

use think\Request;

class JwtHandler
{
    /**
     * 获取请求头中的认证信息
     * @param $jwtKey
     * @return array
     */
    public static function checkJwtFromHeader($jwtKey) {
        $token = input('get.token');
        if(!$token) {
            // 'Authorization': 'Bearer ' + token
            $authorization = request()->header('Authorization');
            if ($authorization == null || $authorization == "") {
                return null;
            }
            if (substr($authorization, 0, 6) != 'Bearer') {
                return null;
            }
    
            $token = substr($authorization, 7);
            if (!$token) {
                return null;
            }
        }
        try {
            $jwt = self::decode($jwtKey, $token) ;
        }
        catch (\Exception $e) {
            return null;
        }
        return $jwt;
    }

    public static function encode($jwtKey, $jwtToken) {
        $j = json_encode($jwtToken);
        return base64_encode($j);
    }


    public static function decode($jwtKey, $jwtToken){
        $t = base64_decode($jwtToken);
        return json_decode($t, true);
    }
}